// 获取 URL 参数的函数
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    var results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

// 显示不同的管理界面
function showManagement(type) {
    const mainContent = document.querySelector('.main-content');
    mainContent.innerHTML = ''; // 清空当前内容

    // 根据类型加载不同的管理界面
    if (type === 'users') {
        loadUsers();
    } else if (type === 'products') {
        loadProducts();
    } else if (type === 'orders') {
        loadOrders();
    } else if (type === 'inventory') {
        loadInventory();
    }
}

// 加载订单列表
function loadOrders() {
    fetch('http://localhost:8080/orders')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(orders => {
            const mainContent = document.querySelector('.main-content');
            mainContent.innerHTML = `
                <button onclick="window.location.href='addOrderDetail.html'">新建订单</button>
                <table class="table">
                    <thead>
                        <tr>
                            <th>订单ID</th>
                            <th>用户ID</th>
                            <th>总金额</th>
                            <th>状态</th>
                            <th>订单日期</th>
                            <th>详情</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${orders.map(order => `
                            <tr>
                                <td>${order.orderID}</td>
                                <td>${order.userID}</td>
                                <td>${order.totalAmount}</td>
                                <td>${order.status}</td>
                                <td>${order.orderDate}</td>
                                <td>
                                    ${order.details.map(detail => `
                                        <div>
                                            <img src="${detail.product.imageURL}" alt="${detail.product.name}" style="width:50px;height:50px;">
                                            <p>${detail.product.name}</p>
                                            <p>数量: ${detail.quantity}</p>
                                            <p>单价: ${detail.unitPrice}</p>
                                            <p>小计: ${detail.subtotal}</p>
                                        </div>
                                    `).join('')}
                                </td>
                                <td>
                                    <button class="btn btn-primary" onclick="window.location.href='editOrder.html?id=${order.orderID}'">编辑</button>
                                    <button class="btn btn-danger" onclick="window.location.href='deleteOrderDetail.html?id=${order.orderID}'">删除</button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        })
        .catch(error => {
            console.error('Error fetching orders:', error);
            alert('无法加载订单信息');
        });
}

// 加载用户列表
function loadUsers() {
    fetch('http://localhost:8080/users')
        .then(response => response.json())
        .then(users => {
            const mainContent = document.querySelector('.main-content');
            mainContent.innerHTML = `
                <h2>用户列表</h2>
                <button onclick="window.location.href='addUser.html'">新建用户</button>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Username</th>
                            <th>Email</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${users.map(user => `
                            <tr>
                                <td>${user.name}</td>
                                <td>${user.email}</td>
                                <td>
                                    <button class="btn btn-primary" onclick="window.location.href='editUser.html?id=${user.userID}'">编辑</button>
                                    <button class="btn btn-danger" onclick="window.location.href='deleteUser.html?id=${user.userID}'">删除</button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        });
}

// 加载产品列表
function loadProducts() {
    fetch('http://localhost:8080/products')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(products => {
            const mainContent = document.querySelector('.main-content');
            mainContent.innerHTML = `
                <button onclick="window.location.href='addProduct.html'">新建产品</button>
                <table class="table">
                    <thead>
                        <tr>
                            <th>图片</th>
                            <th>产品名称</th>
                            <th>描述</th>
                            <th>价格</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${products.map(product => `
                            <tr>
                                <td><img src="${product.imageURL}" alt="${product.name}" style="width:100px;height:100px;"></td>
                                <td>${product.name}</td>
                                <td>${product.description}</td>
                                <td>${product.price}</td>
                                <td>
                                    <button class="btn btn-primary" onclick="window.location.href='editProduct.html?id=${product.productID}'">编辑</button>
                                    <button class="btn btn-danger" onclick="window.location.href='deleteProduct.html?id=${product.productID}'">删除</button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        })
        .catch(error => {
            console.error('Error fetching products:', error);
            alert('无法加载产品信息');
        });
}

// 加载库存列表
function loadInventory() {
    fetch('http://localhost:8080/inventory')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(inventory => {
            const mainContent = document.querySelector('.main-content');
            mainContent.innerHTML = `
                <button onclick="window.location.href='addInventory.html'">新建库存</button>
                <table class="table">
                    <thead>
                        <tr>
                            <th>产品ID</th>
                            <th>数量</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${inventory.map(item => `
                            <tr>
                                <td>${item.productID}</td>
                                <td>${item.stockQuantity}</td>
                                <td>
                                    <button class="btn btn-primary" onclick="window.location.href='editInventory.html?id=${item.productID}'">编辑</button>
                                    <button class="btn btn-danger" onclick="window.location.href='deleteInventory.html?id=${item.productID}'">删除</button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
        })
        .catch(error => {
            console.error('Error fetching inventory:', error);
            alert('无法加载库存信息');
        });
}

// 删除库存项的函数
function deleteInventory(id) {
    if (!confirm('确定要删除这个库存项吗？')) {
        return; // 如果用户取消，则不执行任何操作
    }

    fetch(`http://localhost:8080/inventory/${id}`, {
        method: 'DELETE',
        credentials: 'include'
    })
        .then(response => {
            if (response.ok) {
                alert('库存项已删除');
                loadInventory(); // 重新加载库存列表
            } else {
                throw new Error('Failed to delete inventory item');
            }
        })
        .catch(error => {
            console.error('Error deleting inventory item:', error);
            alert('删除库存项失败');
        });
}

// 切换侧边栏的显示和隐藏
function toggleSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const mainContent = document.querySelector('.main-content');
    const toggleBtn = document.querySelector('.toggle-sidebar-btn');

    // 切换侧边栏的 'hidden' 类
    sidebar.classList.toggle('hidden');
    mainContent.classList.toggle('sidebar-hidden');

    // 根据侧边栏的状态更新按钮的文本
    toggleBtn.innerText = sidebar.classList.contains('hidden') ? '☰' : '✕';
}

// 页面加载时执行的函数
document.addEventListener('DOMContentLoaded', function() {
    // 默认加载订单管理界面
    showManagement('orders');

    // 获取 URL 中的参数 'id'
    var id = getParameterByName('id');
    if (id) {
        var pathname = window.location.pathname;
        if (pathname.includes('editUser.html')) {
            openEditUserForm(id);
        } else if (pathname.includes('editProduct.html')) {
            openEditProductForm(id);
        } else if (pathname.includes('editOrder.html')) {
            openEditOrderForm(id);
        } else if (pathname.includes('editOrderDetail.html')) {
            openEditOrderDetailForm(id);
        } else if (pathname.includes('editInventory.html')) {
            openEditInventoryForm(id);
        }
    }
});

// 打开编辑用户表单
function

openEditUserForm(id) {
    window.location.href = `editUser.html?id=${id}`;
}

// 打开编辑产品表单
function openEditProductForm(id) {
    window.location.href = `editProduct.html?id=${id}`;
}

// 打开编辑订单表单
function openEditOrderForm(id) {
    window.location.href = `editOrder.html?id=${id}`;
}

// 打开编辑订单详情表单
function openEditOrderDetailForm(id) {
    window.location.href = `editOrderDetail.html?id=${id}`;
}

// 打开编辑库存表单
function openEditInventoryForm(id) {
    window.location.href = `editInventory.html?id=${id}`;
}
function performSearch(searchTerm) {
    const mainContent = document.querySelector('.main-content');
    const currentPage = mainContent.getAttribute('data-current-page');
    switch (currentPage) {
        case 'usersPage':
            searchUsers(searchTerm);
            break;
        case 'productsPage':
            searchProducts(searchTerm);
            break;
        case 'ordersPage':
            searchOrders(searchTerm);
            break;
        case 'inventoryPage':
            searchInventory(searchTerm);
            break;
        default:
            alert('无法确定当前页面，无法进行搜索。');
    }
}

function searchUsers(searchTerm) {
    fetch(`/global-search?q=${encodeURIComponent(searchTerm)}`)
        .then(response => response.json())
        .then(users => {
            displayUsers(users);
        })
        .catch(error => console.error('Error fetching users:', error));
}

function searchProducts(searchTerm) {
    fetch(`/global-search?q=${encodeURIComponent(searchTerm)}`)
        .then(response => response.json())
        .then(products => {
            displayProducts(products);
        })
        .catch(error => console.error('Error fetching products:', error));
}

function searchOrders(searchTerm) {
    fetch(`/global-search?q=${encodeURIComponent(searchTerm)}`)
        .then(response => response.json())
        .then(orders => {
            displayOrders(orders);
        })
        .catch(error => console.error('Error fetching orders:', error));
}

function searchInventory(searchTerm) {
    fetch(`/global-search?q=${encodeURIComponent(searchTerm)}`)
        .then(response => response.json())
        .then(inventory => {
            displayInventory(inventory);
        })
        .catch(error => console.error('Error fetching inventory:', error));
}

// 以下为显示结果的示例函数，您需要根据实际的HTML结构进行调整
function displayUsers(users) {
    const usersContainer = document.querySelector('.users-container');
    usersContainer.innerHTML = users.map(user => `
        <div>
            <p>${user.username}</p>
            <p>${user.email}</p>
        </div>
    `).join('');
}

function displayProducts(products) {
    const productsContainer = document.querySelector('.products-container');
    productsContainer.innerHTML = products.map(product => `
        <div>
            <p>${product.name}</p>
            <p>${product.description}</p>
        </div>
    `).join('');
}

function displayOrders(orders) {
    const ordersContainer = document.querySelector('.orders-container');
    ordersContainer.innerHTML = orders.map(order => `
        <div>
            <p>${order.orderNumber}</p>
            <p>${order.customerName}</p>
        </div>
    `).join('');
}

function displayInventory(inventory) {
    const inventoryContainer = document.querySelector('.inventory-container');
    inventoryContainer.innerHTML = inventory.map(item => `
        <div>
            <p>${item.productName}</p>
            <p>${item.quantity}</p>
        </div>
    `).join('');
}
document.getElementById('userSearchButton').addEventListener('click', function () {
    const searchTerm = document.getElementById('userSearchInput').value;
    performUserSearch(searchTerm);
});